import Worker from './worker.js?worker'

export const cutFile = async (params) => {
    return new Promise((resolve, reject) => {
        const { file, CHUNK_SIZE = 1024 * 1024 * 5 } = params
        const result = []
        let finishCount = 0
        // 线程数量
        const THREAD_COUNT = navigator.hardwareConcurrency || 4
        // 分片数量
        const chunkCount = Math.ceil(file.size / CHUNK_SIZE)
        // 每个线程分片数量
        const threadChunkCount = Math.ceil(chunkCount / THREAD_COUNT)
        for (let i = 0; i < THREAD_COUNT; i++) {
            // 开启一个线程
            const worker = new Worker()
            let start = i * threadChunkCount
            let end =  Math.min(start + threadChunkCount, chunkCount)
            worker.postMessage({
                file,
                start,
                end,
                CHUNK_SIZE
            })
            worker.onmessage = (e) => {
                worker.terminate()
                result[i] = e.data
                finishCount++
                if (finishCount === THREAD_COUNT) {
                    resolve(result.flat())
                }
            }
        }
    })
}
